package cn.swenty.backstage.framework.controller.enums;

import java.util.List;
import java.util.Map;

import cn.swenty.backstage.framework.common.util.StringUtil;
import cn.swenty.backstage.framework.controller.core.Result;
import cn.swenty.backstage.framework.util.JsonUtils;

/**
 * api 调用结果返回状态
 * 
 * @author sunyang
 *
 */
public enum Status {

	SUCCESS("1", "{\"state\":1,\"result\":\"${result}\"}"), 
	NO_DEAL("0", "{\"state\":0,\"result\":\"no deal\"}"), 
	ERROR("-1", "{\"state\":-1,\"error_code\":${error_code},\"error\":\"${error}\",\"describe\":\"${describe}\"}");

	private Status(String code, String json) {
		this.code = code;
		this.json = json;
	}

	// 获取status
	public static Status get(String code) {
		for (Status c : Status.values()) {
			if (c.getCode().equals(code)) {
				return c;
			}
		}
		return null;
	}

	// 获取json
	public static String getJson(String code) {
		for (Status c : Status.values()) {
			if (c.getCode().equals(code)) {
				return c.json;
			}
		}
		return null;
	}

	private String json;
	private String code;

	public String getJson() {
		return json;
	}
	
	public static Result getSuccessJson(String result){
		return getResult(JsonUtils.parseJSONMap(SUCCESS.json.replace("${result}", result==null?"":result)));
	}
	
	public static Result getSuccessJson(Map<String, Object> result){
		return getResult(JsonUtils.parseJSONMap( SUCCESS.json.replace("\"${result}\"", result==null?"":JsonUtils.mapToJson(result))));
	}
	
	public static Result getSuccessJson(List<? extends Map<String, Object>> result){
		return getResult(JsonUtils.parseJSONMap( SUCCESS.json.replace("\"${result}\"", result==null?"":JsonUtils.listToJson(result))));
	}
	
	public static Result getErrorJson(Error error){
		return getResult(JsonUtils.parseJSONMap( ERROR.json.replace("${error_code}", error.getCode()).replace("${error}", StringUtil.isNull(error.getError())?"":error.getError()).replace("${describe}", StringUtil.isNull(error.getDescribe())?"":error.getDescribe())));
	}
	public static String getNoDeal(){
		return NO_DEAL.json;
	}
	public void setJson(String json) {
		this.json = json;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	
	public static Result getResult(Map<String, Object> map){
		Result result = new Result();
		result.putAll(map);
		return result;
	}
	
}
